package com.chaofan.websocket.Web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaofan.websocket.Model.User;
import com.chaofan.websocket.entity.*;
import com.chaofan.websocket.mapper.*;
import com.chaofan.websocket.service.AgentInfoService;
import com.chaofan.websocket.service.MsgRecordService;
import com.chaofan.websocket.service.UpdownBranchService;
import com.chaofan.websocket.service.WeixinUserService;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.management.resources.agent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Chaofan at 2018/7/6 9:39
 * email:chaofan2685@qq.com
 **/

@RestController
@RequestMapping("/ws")
public class SocketController {

    private static final Logger logger = LoggerFactory.getLogger(SocketController.class);

//    //图片保存路径
//    private String imgPath = new ApplicationHome(this.getClass()).getSource().getParentFile().toString()+"/img/";

    ApplicationHome home = new ApplicationHome(this.getClass());
    File sysfile = home.getDir();
    String imgPath = sysfile.getParentFile().toString()+"/img/";

    public static HashSet weixinIdMap=new HashSet<>();

    public static Map<Long,String> img = new HashMap();

    @Autowired
    private MsgRecordService msgRecordService;

    @Autowired
    private MsgRecordMapper msgRecordMapper;

    @Autowired
    private MsgRecordPoJOMapper msgRecordPoJOMapper;

    @Autowired
    private WeixinUserService weixinUserService;

    @Autowired
    private MyWebSocket myWebSocket;

    @Autowired
    private WeixinUserMapper weixinUserMapper;

    @Autowired
    private PrizeRecordMapper prizeRecordMapper;

    @Autowired
    private LuckRecordMapper luckRecordMapper;

    @Autowired
    private PrizeConfigMapper prizeConfigMapper;

    @Autowired
    private UpdownBranchService updownBranchService;

    @Autowired
    private AgentInfoMapper agentInfoMapper;

    @Value("${image.url}")
    private String url;

    private Gson gson = new Gson();


    public static void main(String[] args) {
        String s="1";
        Integer s1 = s.split(",").length;
        System.out.println(s1);
    }

    @PostMapping("/test")
    public synchronized void test(HttpServletRequest request){
        String sendMsg = request.getParameter("sendMsg");
        String room = request.getParameter("room");
        String type = request.getParameter("type");
        Map<String,String> rootResult = new HashMap<>();
        MsgRecord msgRecord = new MsgRecord();
        if (type==null) {
            rootResult.put("type","msg");
            msgRecord.setType(1);
            msgRecord.setMsg(sendMsg);
            rootResult.put("msg",sendMsg);
        }else{
            rootResult.put("type",type);
            msgRecord.setType(2);
            msgRecord.setMsg(url+sendMsg);
            rootResult.put("msg",url+sendMsg);
        }
        rootResult.put("sendUser","机器人");
        rootResult.put("shake","");
        HashMap<String, CopyOnWriteArraySet<User>> userForRoom = MyWebSocket.UserForRoom;
        msgRecord.setRoomId(room);
        msgRecord.setWexinName("机器人");
        msgRecord.setCreateTime(DateUtil.date());

        msgRecordService.save(msgRecord);
        HashMap<String, CopyOnWriteArraySet<User>> userForRoom1 = MyWebSocket.UserForRoom;
        CopyOnWriteArraySet<User> users = MyWebSocket.UserForRoom.get(room);
        if(users !=null){
            myWebSocket.sendRoomMessagesOther(users,gson.toJson(rootResult));
        }
    }

    @PostMapping("/toRoot")
    public  void toRoot(HttpServletRequest request) throws InterruptedException {
                    PrizeRecord notPrizeRecord = prizeRecordMapper.getMaxPrizeRecordByPrizeTime();
                    PrizeConfig intervalInfo = prizeConfigMapper.selectAdminPrizeConfigByKey("interval");
                    PrizeConfig sealingTime = prizeConfigMapper.selectAdminPrizeConfigByKey("sealingTime");
                    int sealingTimeValue = Integer.valueOf(sealingTime.getConfigValue()).intValue();
                    int intValue = Integer.valueOf(intervalInfo.getConfigValue()).intValue();
                    //大于开始时间 小于封盘时间
                    Date sealingDate = DateUtil.offsetMinute(notPrizeRecord.getPrizeTime(), -sealingTimeValue);
                    Date intValueDate = DateUtil.offsetMinute(notPrizeRecord.getPrizeTime(), -intValue);
                    if (DateUtil.date().getTime() > intValueDate.getTime() && DateUtil.date().getTime() < sealingDate.getTime()) {
                        String sendMsg = request.getParameter("sendMsg");
                        String room = request.getParameter("room");
                        String wexinId = request.getParameter("wexinId");
                        Map<String,String> rootResult = new HashMap<>();
                        QueryWrapper<WeixinUser> queryWrapperSdf = new QueryWrapper<>();
                        queryWrapperSdf.lambda().eq(WeixinUser::getWexinId,wexinId).eq(WeixinUser::getRoom,room);
                        WeixinUser weixinUser = weixinUserMapper.selectOne(queryWrapperSdf);
                        String wexinName = weixinUser.getWexinName();
                        String endStr="";
                        Double endNum =0.00;
                        if (sendMsg.contains("球")) {
                            try {
                                endStr = substring(sendMsg, 2);
                                endNum =Double.valueOf(endStr);
                                endNum= new Double(String.format("%.2f",endNum));
                                Double price = Double.valueOf(weixinUser.getPrice());
                                if (endNum>price) {
                                    return;
                                }
                            }catch (Exception e){
                                return;
                            }
                        }else if(sendMsg.contains("上分")){
                            QueryWrapper<UpdownBranch> updownBranch = new QueryWrapper<>();
                            updownBranch.lambda().eq(UpdownBranch::getWexinId,wexinId).eq(UpdownBranch::getRoom,room).eq(UpdownBranch::getAuditStatus,0).eq(UpdownBranch::getBranchType,1);
                            UpdownBranch updownBranchRecord = updownBranchService.getOne(updownBranch);
                            if (updownBranchRecord!=null) {
                                return;
                            }
                        }else if(sendMsg.contains("下分")){
                            QueryWrapper<UpdownBranch> updownBranch = new QueryWrapper<>();
                            updownBranch.lambda().eq(UpdownBranch::getWexinId,wexinId).eq(UpdownBranch::getRoom,room).eq(UpdownBranch::getAuditStatus,0).eq(UpdownBranch::getBranchType,2);
                            UpdownBranch updownBranchRecord = updownBranchService.getOne(updownBranch);
                            if (updownBranchRecord!=null) {
                                return;
                            }
                        }
                        MsgRecord msgRecord = new MsgRecord();
                        rootResult.put("type","msg");
                        msgRecord.setType(1);
                        msgRecord.setMsg(sendMsg);
                        rootResult.put("msg",sendMsg);
                        rootResult.put("sendUser",wexinName);
                        rootResult.put("image",weixinUser.getImage());
                        rootResult.put("state","1");
                        rootResult.put("shake","");
                        HashMap<String, CopyOnWriteArraySet<User>> userForRoom = MyWebSocket.UserForRoom;
                        msgRecord.setRoomId(room);
                        msgRecord.setWexinName(wexinName);
                        msgRecord.setWexinId(wexinId);
                        msgRecord.setCreateTime(DateUtil.date());
                        msgRecordService.save(msgRecord);
                        HashMap<String, CopyOnWriteArraySet<User>> userForRoom1 = MyWebSocket.UserForRoom;
                        CopyOnWriteArraySet<User> users = MyWebSocket.UserForRoom.get(room);
                        if (users!=null) {
                            myWebSocket.sendRoomMessagesOther(users,gson.toJson(rootResult));
                            myWebSocket.rootSendMessageOne(sendMsg,wexinName,wexinId,room);
                        }else{
                            myWebSocket.noUserSendOther(sendMsg,wexinName,wexinId,room);
                        }
                    }else {
                        return;
                    }
    }

    @PostMapping("/toLuckRoot")
    public  void toLuckRoot(HttpServletRequest request) throws InterruptedException {
                    String room = request.getParameter("room");
                    QueryWrapper<AgentInfo> agentInfoQueryWrapper = new QueryWrapper<>();
                    agentInfoQueryWrapper.lambda().eq(AgentInfo::getRoom,room);
                    AgentInfo agentInfo = agentInfoMapper.selectOne(agentInfoQueryWrapper);
                    if (agentInfo.getAgentState()==2) {
                        return;
                    }
                    PrizeRecord notPrizeRecord = prizeRecordMapper.getMaxPrizeRecordByPrizeTime();
                    PrizeConfig intervalInfo = prizeConfigMapper.selectAdminPrizeConfigByKey("interval");
                    PrizeConfig sealingTime = prizeConfigMapper.selectAdminPrizeConfigByKey("sealingTime");
                    int sealingTimeValue = Integer.valueOf(sealingTime.getConfigValue()).intValue();
                    int intValue = Integer.valueOf(intervalInfo.getConfigValue()).intValue();
                    //大于开始时间 小于封盘时间
                    Date sealingDate = DateUtil.offsetMinute(notPrizeRecord.getPrizeTime(), -sealingTimeValue);
                    Date intValueDate = DateUtil.offsetMinute(notPrizeRecord.getPrizeTime(), -intValue);
                    if (DateUtil.date().getTime() > intValueDate.getTime() && DateUtil.date().getTime() < sealingDate.getTime()) {
                        String sendMsg = request.getParameter("sendMsg");

                        String wexinId = request.getParameter("wexinId");
                        Map<String,String> rootResult = new HashMap<>();
                        QueryWrapper<WeixinUser> queryWrapperSdf = new QueryWrapper<>();
                        queryWrapperSdf.lambda().eq(WeixinUser::getWexinId,wexinId).eq(WeixinUser::getRoom,room);
                        WeixinUser weixinUser = weixinUserMapper.selectOne(queryWrapperSdf);
                        String wexinName = weixinUser.getWexinName();
                        String endStr="";
                        Double endNum =0.00;
                        if(sendMsg.contains("上分")){
                            QueryWrapper<UpdownBranch> updownBranch = new QueryWrapper<>();
                            updownBranch.lambda().eq(UpdownBranch::getWexinId,wexinId).eq(UpdownBranch::getRoom,room).eq(UpdownBranch::getAuditStatus,0).eq(UpdownBranch::getBranchType,1);
                            UpdownBranch updownBranchRecord = updownBranchService.getOne(updownBranch);
                            if (updownBranchRecord!=null) {
                                return;
                            }
                        }else if(sendMsg.contains("下分")){
                            QueryWrapper<UpdownBranch> updownBranch = new QueryWrapper<>();
                            updownBranch.lambda().eq(UpdownBranch::getWexinId,wexinId).eq(UpdownBranch::getRoom,room).eq(UpdownBranch::getAuditStatus,0).eq(UpdownBranch::getBranchType,2);
                            UpdownBranch updownBranchRecord = updownBranchService.getOne(updownBranch);
                            if (updownBranchRecord!=null) {
                                return;
                            }
                        } else  {
                            try {
                                int startNum=0;
                                String command="";
                                if (sendMsg.contains("番")) {
                                    command="番";
                                    startNum= sendMsg.indexOf("番");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("角")){
                                    command="角";
                                    startNum= sendMsg.indexOf("角");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("车")){
                                    command="车";
                                    startNum= sendMsg.indexOf("车");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("念")){
                                    command="/";
                                    startNum= sendMsg.indexOf(command);
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("堂")){
                                    command="堂";
                                    startNum= sendMsg.indexOf("堂");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("通")){
                                    command="/";
                                    startNum= sendMsg.indexOf(command);
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("单")){
                                    command="单";
                                    startNum= sendMsg.indexOf("单");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("双")){
                                    command="双";
                                    startNum= sendMsg.indexOf("双");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("大")){
                                    command="大";
                                    startNum= sendMsg.indexOf("大");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("小")){
                                    command="小";
                                    startNum= sendMsg.indexOf("小");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }else if(sendMsg.contains("特")){
                                    command="特";
                                    startNum= sendMsg.indexOf("特");
                                    String strOne=sendMsg.substring(startNum,sendMsg.length());
                                    String str = strOne.replaceAll(command, "");
                                    endNum = Double.valueOf(str);
                                }
                            }catch (Exception e){
                                return;
                            }
                        }
                        MsgRecord msgRecord = new MsgRecord();
                        rootResult.put("type","msg");
                        msgRecord.setType(1);
                        msgRecord.setMsg(sendMsg);
                        rootResult.put("msg",sendMsg);
                        rootResult.put("sendUser",wexinName);
                        rootResult.put("image",weixinUser.getImage());
                        rootResult.put("state","1");
                        rootResult.put("shake","");
                        HashMap<String, CopyOnWriteArraySet<User>> userForRoom = MyWebSocket.UserForRoom;
                        msgRecord.setRoomId(room);
                        msgRecord.setWexinName(wexinName);
                        msgRecord.setWexinId(wexinId);
                        msgRecord.setCreateTime(DateUtil.date());
                        msgRecordService.save(msgRecord);
                        HashMap<String, CopyOnWriteArraySet<User>> userForRoom1 = MyWebSocket.UserForRoom;
                        CopyOnWriteArraySet<User> users = MyWebSocket.UserForRoom.get(room);
                        if (users!=null) {
                            myWebSocket.sendRoomMessagesOther(users,gson.toJson(rootResult));
                            myWebSocket.rootSendMessageTwo(sendMsg,wexinName,wexinId,room);
                        }else{
                            myWebSocket.noUserSendOtherOne(sendMsg,wexinName,wexinId,room);
                        }
                    }else {
                        return;
                    }

    }

    public String substring(String str,int startNum,int endNum){
        String substring = str.substring(startNum,endNum);
        return substring;
    }

    public String substring(String str,int num){
        String substring = str.substring(num);
        return substring;
    }


    private static int getRandomStartToEnd(int x, int y) {
        int num = -1;
        //说明：两个数在合法范围内，并不限制输入的数哪个更大一些
        if (x < 0 || y < 0) {
            return num;
        } else {
            int max = Math.max(x, y);
            int min = Math.min(x, y);
            int mid = max - min;//求差
            //产生随机数
            num = (int) (Math.random() * (mid + 1)) + min;
        }
        return num;
    }

    /**
     * 根据房间号获得其中的用户
     * @param room 房间号
     * @return
     */
    @RequestMapping("/online")
    public Map<String,Object> online(HttpServletResponse response, String room){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        Map<String,Object> result = new HashMap<>();
        CopyOnWriteArraySet<User> rooms = MyWebSocket.UserForRoom.get(room);
//        List<String> nicks = new ArrayList<>();
        List<Map<String,String>> users = new ArrayList<>();
        if (rooms != null){
            rooms.forEach(user -> {
                Map<String,String> map = new HashMap<>();
                map.put("nick",user.getNickname());
                map.put("id",user.getId());
                users.add(map);
            });
            result.put("onlineNum",rooms.size());
            result.put("onlineUsera",users);
        }else {
            result.put("onlineNum",0);
            result.put("onlineUsera",null);
        }
        return result;
    }

    /**
     * 判断昵称在某个房间中是否已存在，房间是否有密码，如果有，用户输入的密码又是否正确
     * @param room 房间号
     * @param nick 昵称
     * @param pwd 密码
     * @return
     */
    @RequestMapping("/judgeNick")
    public Map<String,Object> judgeNick(HttpServletResponse response, String room, String nick, String pwd,String wexinId){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        Map<String,Object> result = new HashMap<>();
        result.put("code",0);
        CopyOnWriteArraySet<User> rooms = MyWebSocket.UserForRoom.get(room);
        if (rooms != null){
            rooms.forEach(user -> {
                if (user.getNickname().equals(wexinId)){
                    result.put("code",1);
                    result.put("msg","微信id已存在，请重新输入");
                    logger.debug("有重复");
                }
            });
            if ((Integer)result.get("code") != 0){
                return result;
            }
            String password = MyWebSocket.PwdForRoom.get(room);
            if (StrUtil.isNotEmpty(password) && !(pwd.equals(password))){
                result.put("code",2);
                result.put("msg","密码错误，请重新输入");
                return result;
            }else {
                result.put("code",3);
                result.put("msg","房间无密码");
                return result;
            }
        }
        return result;
    }

    @RequestMapping("/getAllMessage")
    public IPage<MsgRecordPoJO> getAllMessage(HttpServletResponse response, String room, int pageNum, int pageSize){

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        Page<MsgRecordPoJO> page = new Page<>(pageNum,pageSize);
        Map map=new HashMap();
        map.put("roomId", room);
        IPage<MsgRecordPoJO> list = msgRecordPoJOMapper.selectAllMsg(page, map);
        return list;
    }




    /**
     * 实现文件上传
     * */
    @RequestMapping("/fileUpload")
    public Map<String,Object> fileUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        Map<String,Object> result = new HashMap<>();
        //获取项目访问路径
        String root = request.getRequestURL().toString().replace(request.getRequestURI(),"");
        if(file.isEmpty()){
            return null;
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //重命名文件
        String imgName = RandomUtil.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        logger.debug("上传图片保存在：" + imgPath + imgName);
        File dest = new File(imgPath + imgName);
        img.put(System.currentTimeMillis(),imgPath + imgName);
        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(dest);
            //返回图片访问路径
            result.put("url",root +"/img/" + imgName);
            logger.debug("图片保存成功，访问路径为："+result.get("url"));
            return result;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            logger.error("图片保存失败！");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("图片保存失败！");
        }
        return null;
    }

    /**
     * 获取所有房间
     * @return
     */
    @RequestMapping("/allRoom")
    public Map<String,Object> allRoom(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        Map<String,Object> result = new HashMap<>();
        HashMap<String,CopyOnWriteArraySet<User>> userForRoom = MyWebSocket.UserForRoom;
        List<String> rooms = new ArrayList<>();
        for (String key : userForRoom.keySet()) {
            rooms.add(key);
        }
        result.put("rooms",rooms);
        return result;
    }

}
